'use strict';
var fs = require("fs");
var path = require('path');
var _ = require('underscore');
var moment = require('moment');
var crypto = require('crypto');
var cached = {};
var map = {
  'compressed': ['zip', 'rar', 'gz', '7z'],
  'text': ['txt', 'md', ''],
  'image': ['jpg', 'jpge', 'png', 'gif', 'bmp'],
  'pdf': ['pdf'],
  'css': ['css'],
  'js': ['js'],
  'html': ['html'],
  'word': ['doc', 'docx'],
  'excel': ['xls', 'xlsx', 'xlsm'],
  'powerpoint': ['ppt', 'pptx'],
  'movie': ['mkv', 'avi', 'rmvb'],
};
// 数据完整性校验
function getFileType(ext){
	var type=cached[ext];
	if (!type) {
		for (var key in map) {
			if (_.include(map[key], ext)) {
				cached[ext] = key;
				type=key;
				break;
			}
		}
	}
	if (!type){type = 'blank';}
	return type;
}

var getResult=function(stats,fullPath,rootKey,rootPath){
	var dirpath=path.dirname(fullPath);
    dirpath=dirpath.substr(rootPath.length,dirpath.length);
	dirpath=dirpath.replace(new RegExp(/(\\)/g),"/");
	if(!dirpath||dirpath.length<=0){
		dirpath= "/"+rootKey;
	}else{
		dirpath= "/"+rootKey+"/"+dirpath;
	}
	var result = {
	root:rootKey,
	name: path.basename(fullPath),
	rel_path: path.normalize(fullPath),
	path: dirpath,
	type: 'blank',
	file_md5: '',
	file_sha1: '',
  };
  if (stats.isDirectory()){
	result.type = 'folder';   
  }else if(stats.isFile()){
	var ext = path.extname(fullPath).substr(1);
	result.type=getFileType(ext);  
  }
  result.dev=stats.dev;
  result.ino=stats.ino;
  result.mode=stats.mode;
  result.nlink=stats.nlink;
  result.uid=stats.uid;
  result.gid=stats.gid;
  result.rdev=stats.rdev;
  result.size=stats.size;
  result.blksize=stats.blksize;
  result.blocks=stats.blocks;
  result.atime=moment(stats.atime).format("YYYY-MM-DD HH:mm:ss");
  result.ctime=moment(stats.ctime).format("YYYY-MM-DD HH:mm:ss");
  result.mtime=moment(stats.mtime).format("YYYY-MM-DD HH:mm:ss");
  result.birthtime=moment(stats.birthtime).format("YYYY-MM-DD HH:mm:ss");
  return result;
}
var getFileName=function(targetPath){
   targetPath=path.normalize(targetPath);
   var ext = path.extname(targetPath);
   var dirname = path.dirname(targetPath);
   var basename = path.basename(targetPath,ext); 
   var reg = /\(([0-9]+)\b\)/;
   var num=1;
   if(reg.test(basename)){
		num=basename.match(reg)[0].match(/[0-9]+/);;
		num=Number(num)+1;
		basename= basename.replace(reg,"("+num+")"); 
   }else{
	   basename=basename+" ("+num+")";
   }
	targetPath=path.normalize(dirname+path.sep+basename+ext);	
	return targetPath;
}
module.exports={
	getFileName,
	getResult
};